const {
  queryFaultTypeOptions
} = require('../../api/faultType')
const {
  queryMaintenanceModeOptions
} = require('../../api/maintenanceMode')
const { clearEmptyKey } = require('../../utils/clearEmptyKey')
const {
  uploadImg,
  addSupplementaryWorkOrder
} = require('../../api/workOrder')
const {
  queryAllAssetsType
} = require('../../api/assetsType')
const {
  queryAllEventLevel
} = require('../../api/eventLevel')
const {
  SERVICE_MODE,
  DIFFICUIT_FAULT
} = require('../../constant/index')
const { FormatDate } = require('../../utils/FormDate')
const {
  to,
  getEventData,
  showToast,
  openLoading,
  closeLoading,
  routeWithToken,
  backParentLoad
} = getApp()
Page({
  data: {
    DIFFICUIT_FAULT,
    fileList: [],
    formData: {
      faultImg: [],
      addPartsOutParams: [],
      serviceMode: SERVICE_MODE.repair,
      difficultFault: DIFFICUIT_FAULT.not,
      solution: '',
      eventLevelId: '',
      timeList: [new FormatDate().format('yyyy-MM-dd hh:mm'), new FormatDate().format('yyyy-MM-dd hh:mm')]
    },
    assetsTypeOptions: [],
    faultTypeOptions: [],
    maintenanceModeOptions: [],
    eventLevel: [],
    difficultFaultOptions: [{
      name: DIFFICUIT_FAULT.not,
      text: '否'
    }, {
      name: DIFFICUIT_FAULT.yes,
      text: '是'
    }],
    serviceModeOptions: [{
      name: SERVICE_MODE.repair,
      text: '客户报修'
    }, {
      name: SERVICE_MODE.active,
      text: '主动服务'
    }],
    solutionOptions: [{
      name: 1,
      text: '远程'
    }, {
      name: 2,
      text: '现场'
    }]
  },
  onLoad() {
    this.setData({
      ['formData.timeList']: [new FormatDate().format('yyyy-MM-dd hh:mm'), new FormatDate().format('yyyy-MM-dd hh:mm')]
    })
    this.getQueryAllAssetsType();
    this.getQueryAllEventLevel();
  },

  async getQueryAllEventLevel() {
    const [err, data] = await to(queryAllEventLevel({}))
    if (!err) {
      this.setData({
        eventLevel: data
      })
      return Promise.resolve()
    }
    return Promise.reject(err)
  },
  setUserData(data) {
    this.clearForm('launchUserName')
    this.setData(data)
  },
  setDeviceData(data) {
    this.setData(data)
  },
  handleClickUser() {
    routeWithToken('/page-common/custom-user-page/index')
  },

  handleClickDevice() {
    routeWithToken(`/page-common/device-page/index?userId=${ this.data.formData.launchUserId }&assetsTypeId=${ this.data.formData.assetsTypeId }`)
  },

  onCustomFormTypeChange(event) {
    const {
      type
    } = getEventData(event);
    this.setData({
      [`formData.${type}`]: event.detail
    })
    this.clearForm(type)

    if (type === 'assetsTypeId') {
      if (event.detail || event.detail === 0) {
        this.getFaultTypeOptions()
      }
    }
    if (type === 'faultTypeId') {
      if (event.detail || event.detail === 0) {
        this.queryMaintenanceModeOptions()
      }
    }

    if (type === 'serviceMode') {
      if (event.detail || event.detail === 0) {
        this.getFaultTypeOptions()
      }
    }
  },

  clearForm(type) {
    let clearList = []
    let optionsList = []
    if (type === 'launchUserName') {
      clearList = ['companyName', 'companyId', 'departmentName', 'departmentId', 'assetsName', 'assetsId', 'launchUserName', 'launchUserId', 'assetsTypeName', 'assetsTypeId', 'faultTypeId', 'maintenanceModeId']
      optionsList = ['faultTypeOptions', 'maintenanceModeOptions']
    }

    if (type === 'assetsTypeId') {
      clearList = ['assetsName', 'assetsId', 'faultTypeId', 'maintenanceModeId']
      optionsList = ['faultTypeOptions', 'maintenanceModeOptions']
    }

    if (type === 'assetsName') {
      clearList = ['assetsName', 'assetsId', 'faultTypeId', 'maintenanceModeId']
      optionsList = ['faultTypeOptions', 'maintenanceModeOptions']
    }

    if (type === 'faultTypeId') {
      clearList = ['maintenanceModeId']
      optionsList = ['maintenanceModeOptions']
    }

    if (type === 'serviceMode') {
      clearList = ['faultTypeId', 'maintenanceModeId']
      optionsList = ['faultTypeOptions', 'maintenanceModeOptions']
    }

    for (const item of clearList) {
      this.setData({
        [`formData.${item}`]: ''
      })
    }

    for (const item of optionsList) {
      this.setData({
        [item]: ''
      })
    }
  },

  async getQueryAllAssetsType() {
    openLoading()
    const [err, data] = await to(queryAllAssetsType({}))
    closeLoading()
    if (!err) {
      this.setData({
        assetsTypeOptions: data
      })
      return Promise.resolve()
    }
    return Promise.reject(err)
  },

  async getFaultTypeOptions() {
    const params = {
      assetsTypeId: this.data.formData.assetsTypeId,
      serviceMode: this.data.formData.serviceMode
    }

    if (!params.assetsTypeId && params.assetsTypeId !== 0) {
      return;
    }
    if (!params.serviceMode && params.serviceMode !== 0) {
      return;
    }
    openLoading()
    const [err, data] = await to(queryFaultTypeOptions(params))
    closeLoading()

    if (!err) {
      this.setData({
        faultTypeOptions: data
      })
      return Promise.resolve()
    }
    return Promise.reject(err)
  },

  async queryMaintenanceModeOptions() {
    const params = {
      faultTypeId: this.data.formData.faultTypeId
    }
    openLoading()
    const [err, data] = await to(queryMaintenanceModeOptions(params))
    closeLoading()

    if (!err) {
      this.setData({
        maintenanceModeOptions: data
      })
    }
  },

  onFileChange(event) {
    this.setData({
      fileList: event.detail
    })
  },

  async uploadFile(file) {
    const [err, data] = await to(uploadImg({
      filePath: file
    }))
    if (!err) {
      return Promise.resolve(data)
    }
    return Promise.reject(err)
  },

  onClickAttach() {
    const data = JSON.stringify(this.data.formData.addPartsOutParams);
    routeWithToken(`/page-repair/attachment-page/index?fromRoute=${this.route}&choosedData=${data}`)
  },

  onAttachmentChange(event) {
    this.setData({
      ['formData.addPartsOutParams']: event.detail
    })
  },

  setAttachmentData(data) {
    const addPartsOutParams = this.data.formData.addPartsOutParams

    if (!data) return;
    const index = addPartsOutParams.findIndex(item => item.partsId === data.partsId);

    if (index > -1) {
      addPartsOutParams[index].quantity = +addPartsOutParams[index].quantity + +data.quantity
    } else {
      addPartsOutParams.push({
        partsId: data.partsId,
        quantity: 1,
        storeId: data.storeId,
        companyId: this.data.formData.companyId,
        comments: data.comments,
        partsName: data.partsName,
        storeName: data.storeName,
        quantityUnit: data.quantityUnit,
        partsModel: data.partsModel,
        inventoryQuantity: data.inventoryQuantity
      })
    }

    this.setData({
      ['formData.addPartsOutParams']: addPartsOutParams
    })
  },

  async handleSubmit() {
    const isCheck = this.checkValidate()
    if (!isCheck) return;
    const {
      fileList
    } = this.data;
    const [err, fileData] = await to(Promise.all(fileList.map(item => {
      const result = this.uploadFile(item);
      return result
    })))
    if (!err) {
      this.setData({
        ['formData.faultImg']: fileData
      }, () => {
        this.saveData()
      })
    }
  },

  checkValidate() {
    const { launchUserId, assetsId, faultTypeId, eventLevelId,  maintenanceModeId, timeList, operationContent, difficultFault, innovativeSuggestions, solution } = this.data.formData

    if (!launchUserId && launchUserId !== 0) {
      showToast('请选择报修人员')
      return false
    }

    if (!assetsId && assetsId !== 0) {
      showToast('请选择资源')
      return false
    }

    if (!faultTypeId && faultTypeId !== 0) {
      showToast('请选择故障事件')
      return false
    }

    if (!maintenanceModeId && maintenanceModeId !== 0) {
      showToast('请选择维护方式')
      return false
    }

    if (!solution && solution !== 0) {
      showToast('请选择解决方式')
      return false
    }

    if (!eventLevelId && eventLevelId !== 0) {
      showToast('请选择事件级别')
      return false
    }

    if (!timeList) {
      showToast('请选择工作时间')
      return false
    }

    if (!timeList[0]) {
      showToast('请选择工作开始时间')
      return false
    }

    if (!timeList[1]) {
      showToast('请选择工作结束时间')
      return false
    }

    if (!operationContent) {
      showToast('请输入事件解决说明')
      return false
    }

    if (difficultFault === DIFFICUIT_FAULT.yes) {
      if (!innovativeSuggestions) {
        showToast('请输入创新建议')
        return false
      }
    }

    return true
  },

  async saveData() {
    const {
      formData
    } = this.data
    const params = {
      assetsTypeId: formData.assetsTypeId,
      serviceMode: formData.serviceMode,
      solution: formData.solution,
      faultTypeId: formData.faultTypeId,
      assetsId: formData.assetsId,
      faultImg: formData.faultImg,
      launchUserId: formData.launchUserId,
      innovativeSuggestions: formData.innovativeSuggestions,
      difficultFault: formData.difficultFault,
      maintenanceModeId: formData.maintenanceModeId,
      operationContent: formData.operationContent,
      beginTime: formData.timeList[0],
      endTime: formData.timeList[1],
      companyId: formData.companyId,
      launchContent: formData.launchContent,
      comments: formData.comments,
      eventLevelId: formData.eventLevelId,
      addPartsOutParams: JSON.stringify(formData.addPartsOutParams.map(item => {
        item.companyId = formData.companyId
        return item
      })) || '[]'
    }

    clearEmptyKey(params)
    openLoading()
    const [err] = await to(addSupplementaryWorkOrder(params))
    closeLoading()
    if (!err) {
      showToast({
        message: '保存成功',
        type: 'success',
        mask: true,
        onClose: () => {
          setTimeout(() => {
            backParentLoad()
          }, 1000)
        }
      })
    }
  }
})